#!/usr/bin/env ruby

# ---------------------------------------------------------------------------- #
# Copyright 2002-2023, OpenNebula Project, OpenNebula Systems                  #
#                                                                              #
# Licensed under the Apache License, Version 2.0 (the "License"); you may      #
# not use this file except in compliance with the License. You may obtain      #
# a copy of the License at                                                     #
#                                                                              #
# http://www.apache.org/licenses/LICENSE-2.0                                   #
#                                                                              #
# Unless required by applicable law or agreed to in writing, software          #
# distributed under the License is distributed on an "AS IS" BASIS,            #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.     #
# See the License for the specific language governing permissions and          #
# limitations under the License.                                               #
# ---------------------------------------------------------------------------- #

# mkimage size format host:remote_system_ds/disk.i vmid dsid
#   - size in MB of the image
#   - format for the image
#   - host is the target host to deploy the VM
#   - remote_system_ds is the path for the system datastore in the host
#   - vmid is the id of the VM
#   - dsid is the target datastore (0 is the system datastore)

ONE_LOCATION ||= ENV['ONE_LOCATION']

if !ONE_LOCATION
    RUBY_LIB_LOCATION ||= '/usr/lib/one/ruby'
    GEMS_LOCATION     ||= '/usr/share/one/gems'
else
    RUBY_LIB_LOCATION ||= ONE_LOCATION + '/lib/ruby'
    GEMS_LOCATION     ||= ONE_LOCATION + '/share/gems'
end

# %%RUBYGEMS_SETUP_BEGIN%%
if File.directory?(GEMS_LOCATION)
    real_gems_path = File.realpath(GEMS_LOCATION)
    if !defined?(Gem) || Gem.path != [real_gems_path]
        $LOAD_PATH.reject! {|l| l =~ /vendor_ruby/ }

        # Suppress warnings from Rubygems
        # https://github.com/OpenNebula/one/issues/5379
        begin
            verb = $VERBOSE
            $VERBOSE = nil
            require 'rubygems'
            Gem.use_paths(real_gems_path)
        ensure
            $VERBOSE = verb
        end
    end
end
# %%RUBYGEMS_SETUP_END%%

$LOAD_PATH << RUBY_LIB_LOCATION
$LOAD_PATH << File.dirname(__FILE__)

require 'vcenter_driver'

size = ARGV[0]
path = ARGV[2]
vmid = ARGV[3]
dsid = ARGV[4]

check_valid size, 'size'
check_valid path, 'path'
check_valid vmid, 'vmid'
check_valid dsid, 'dsid'

hostname, img_name = path.split(':')
disk_id = img_name.split('.')[-1]

# Get host ID
host = VCenterDriver::VIHelper.find_by_name(OpenNebula::HostPool, hostname)
host_id = host['ID']

# Get datastore ref
one_ds = VCenterDriver::VIHelper.one_item(OpenNebula::Datastore, dsid)
ds_ref = one_ds['TEMPLATE/VCENTER_DS_REF']

# Get one_vm
one_vm = VCenterDriver::VIHelper.one_item(OpenNebula::VirtualMachine, vmid)

# Adapter and disk type from one_vm
disk_xpath = "/VM/TEMPLATE/DISK[DISK_ID=#{disk_id}]/"

adapter_type = one_vm[disk_xpath+'VCENTER_ADAPTER_TYPE'] ||
               VCenterDriver::VIHelper
               .get_default('IMAGE/TEMPLATE/VCENTER_ADAPTER_TYPE')

disk_type = one_vm[disk_xpath+'VCENTER_DISK_TYPE'] ||
            VCenterDriver::VIHelper
            .get_default('IMAGE/TEMPLATE/VCENTER_DISK_TYPE')

check_valid adapter_type, 'adapter_type'
check_valid disk_type, 'disk_type'

# Volatile images dir from one_vm
ds_volatile_dir = one_vm[disk_xpath+'VCENTER_DS_VOLATILE_DIR'] || 'one-volatile'

begin
    vi_client = VCenterDriver::VIClient.new_from_host(host_id)

    img_name = "#{ds_volatile_dir}/#{vmid}/one-#{vmid}-#{disk_id}"

    ds_vc = VCenterDriver::Storage.new_from_ref(ds_ref, vi_client)

    if ds_vc.class == VCenterDriver::Datastore
        ds_vc.create_virtual_disk(img_name, size, adapter_type, disk_type)
    end
rescue StandardError => e
    message = "Error creating virtual disk in #{ds_vc['name']}."\
              " Reason: #{e.message}}."
    OpenNebula.log_error(message)
    if VCenterDriver::CONFIG[:debug_information]
        STDERR.puts "#{message} #{e.backtrace}"
    end
    exit(-1)
ensure
    vi_client.close_connection if vi_client
end
